<template>
  <div ref="chart" style="width: 100%; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import { listSuggestion } from '@/api/suggestion/suggestion';

export default {
  mounted() {
    this.initChart();
  },
  methods: {
    async initChart() {
      // 获取所有建议数据
      const res = await listSuggestion({ pageSize: 1000 }); // 获取全部数据
      const suggestions = res.rows;

      // 统计分类数据
      const categoryMap = {};
      suggestions.forEach(item => {
        const category = item.category;
        categoryMap[category] = (categoryMap[category] || 0) + 1;
      });

      // 转换字典值
      const dict = this.dict.type.community_suggestion_category;
      const chartData = Object.entries(categoryMap).map(([value, count]) => ({
        name: dict.find(d => d.value === value)?.label || '未知分类',
        value: count
      }));

      // 初始化图表
      const chart = echarts.init(this.$refs.chart);
      chart.setOption(this.getChartOption(chartData));
    },

    getChartOption(data) {
      return {
        title: {
          text: '建议分类占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '分类占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: data
          }
        ]
      };
    }
  },
  // 如果使用字典需要声明
  dicts: ['community_suggestion_category']
};
</script>
